package com.acme.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeSet;
import java.util.logging.Logger;

import com.acme.domain.Order;
import com.acme.domain.Orderstatus;
import com.acme.domain.Stock;
import com.acme.domain.request.*;
import com.acme.domain.response.*;

public class ParseService {
	
	private static Logger parseLogger = Logger.getLogger(ParseService.class.getName());
	
	public static void parseRequest(Request request, Stock stock){
		try{
			if (request instanceof PlaceOrderRequest){
				Order placingOrder = ((PlaceOrderRequest) request).getOrder();
				placingOrder.setStatus(Orderstatus.ACCEPTED);
				if (!ValidateService.validate(placingOrder)) {
					placingOrder.setStatus(Orderstatus.REJECTED);
				} else if (!MatchService.match(placingOrder, (TreeSet<Order>)stock.getOrders())){
					stock.placeOrder(placingOrder);					
				}
				SendService.send(new PlaceOrderResponse(placingOrder));
	
			} else if ( request instanceof CancelOrderRequest) {
				Order orderToCancel = ((CancelOrderRequest) request).getOrder();
				try {
					if (stock.cancelOrder(orderToCancel)){
						
						orderToCancel.setStatus(Orderstatus.CANCELLED);
						SendService.send(new CancelOrderResponse(orderToCancel));
					} else {
						parseLogger.info("Exchange " + orderToCancel.getStockName() + " doesn't " +
								"contain order with id " + orderToCancel.getId() + " to cancel");
					}
				} catch (NullPointerException exc){
					SendService.send(new MsgToClient(exc.getMessage()));
				}
				
				
			} else if (request instanceof AllocateIDRequest){
				SendService.send(new AllocateIDResponse(stock.getCurrentID(),stock.getID_RANGE(), null, stock.getStockName()));
				stock.setCurrentID(stock.getCurrentID()+stock.getID_RANGE());
			} else if (request instanceof SubscribeMarketDataRequest){
				stock.subscribeMarketData(request.getUsername());
				parseLogger.info(request.getUsername() + " subscribed on " +request.getStockName());
				SendService.send( new SubscribeMarketDataResponse(new ArrayList<Order>(stock.getOrders()), request.getUsername()));
			} else if (request instanceof UnsubscribeMarketDataRequest){
				parseLogger.info(request.getUsername() + " unsubscribed from " +request.getStockName());
				stock.unsubscribeMarkedData(request.getUsername());
			} else if (request instanceof SubscribeOrderStateRequest){
				stock.subscribeOrderState(request.getUsername());
				parseLogger.info(request.getUsername() + " subscribed on OrderState");
				SendService.send( new SubscribeOrderStateResponse(new ArrayList<Order>(stock.getOrders()), request.getUsername()));
			} else if (request instanceof UnsubscribeOrderStateRequest){
				parseLogger.info(request.getUsername() + " unsubscribed from OrderState");
				stock.unsubscribeOrderState(request.getUsername());
			}
		} catch(IOException e){
			e.printStackTrace();
		}
		
		
	}
}
